<?php

namespace App\Http\Api\Services;

use App\Exceptions\InvalidRequestException;
use App\Http\Models\Logistics;
use App\Http\Models\LogisticsTask;
use App\Http\Models\Order;
use App\Lib\PHPExcel\ExcelHandle;
use App\Lib\Zhuzhuyun\Zhuzhuyun;
use Illuminate\Support\Facades\DB;


class LogisticsService
{

    /*
     * 物流任务入库
     * */
    public function logisticsTask($arr)
    {
        $taskData = [];
        if (!empty($arr)) {
            foreach ($arr as $item) {
                $taskData[] = [
                    'task_id' => $item['msg'],
                    'kdgs' => $item['tag'],
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ];
            }
        }
        LogisticsTask::insert($taskData);
    }


    /*
     * 物流查询的入库操作
     * */
    public function createTaskAndDetail($arr = [])
    {
        $order_ids = $this->checkDataValid($arr);
        //找出没有入库的订单 Logistics
        $l_order_ids = Logistics::whereIn('order_id', $order_ids)->get()->pluck('order_id')->toArray();
        $insertData = [];
        foreach ($arr as $item) {
            if (!in_array($item['C'], $l_order_ids)) {
                $insertData[] = [
                    'order_id' => $item['C'],
                    'kddh' => $item['A'],
                    'kdgs' => $item['B'],
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ];
            }
        }

        Logistics::insert($insertData);
    }

    /*
     * 校验参数合法性
     * */
    public function checkDataValid($arr = [])
    {
        //把所有的订单id遍历
        //排重 kddh order_id
        $kddhs = [];
        $order_ids = [];

        foreach ($arr as $item) {
            if (!in_array($item['A'], $kddhs)) {
                $kddhs[] = $item['A'];
            } else {
                throw new InvalidRequestException('快递单号' . $item['A'] . '重复');
            }

            if (!in_array($item['C'], $order_ids)) {
                $order_ids[] = $item['C'];
            } else {
                throw new InvalidRequestException('订单号' . $item['C'] . '重复');
            }
        }

        //核查订单是否都有
        $database_order_ids = Order::whereIn('order_id', $order_ids)->get()->pluck('order_id')->toArray();

        foreach ($order_ids as $o_id) {
            if (!in_array($o_id, $database_order_ids)) {
                throw new InvalidRequestException('订单号' . $o_id . '不存在');
            }
        }
        return $order_ids;

    }


    /*
     * 物流通知
     * */
    public function logisticsNotice()
    {
        $this->stagnation();
        $this->writeBackNotice();
        $this->wrongDestination();
    }

    /*
     * 三天停滞的订单
     * */
    public function stagnation()
    {
        //没有签收的订单中 最新更新时间与今天的间隔超过三天的订单
        $query = Logistics::query();
        $now = '"' . date('Y-m-d H:i:s') . '"';
        $raw = DB::raw("TIMESTAMPDIFF(DAY,l.zuixinshijian,$now) as timeLast,l.order_id,o.post_receiver,o.post_tel,o.shop_name");
        $data = $query->from('admin_logistics as l')
            ->select($raw)
            ->leftJoin('admin_orders as o', 'o.order_id', '=', 'l.order_id')
            ->where('l.wuliuzhuangtai', '!=', '已签收')
            ->having('timeLast', '>=', 3)
            ->get()->toArray();

        if (count($data) > 0) {
            $token = '907333c555896d5e87913074a545b53c4c6a90032b186fff38774bcbf39fa674';
            $obj = new \App\Lib\DingDingNotice\LogisticsStagnation($data, $token, $atMobiles = [], $isAtall = false);
            $obj->sendMarkdownMessage();
        }
    }

    /*
     * 三天滞留订单下载
     * */
    public function stagnationExp()
    {
        //没有签收的订单中 最新更新时间与今天的间隔超过三天的订单
        $query = Logistics::query();
        $now = '"' . date('Y-m-d H:i:s') . '"';
        $raw = DB::raw("TIMESTAMPDIFF(DAY,l.zuixinshijian,$now) as timeLast,l.order_id,o.post_receiver,o.post_tel,o.shop_name");
        $data = $query->from('admin_logistics as l')
            ->select($raw)
            ->leftJoin('admin_orders as o', 'o.order_id', '=', 'l.order_id')
            ->where('l.wuliuzhuangtai', '!=', '已签收')
            ->having('timeLast', '>=', 3)
            ->get()->toArray();


        if (count($data) > 0) {

            $arr = [];
            foreach ($data as $it) {
                $arr[] = [
                    'order_id' => $it['order_id'],
                    'shop_name' => $it['shop_name'],
                    'post_receiver' => $it['post_receiver'],
                    'post_tel' => $it['post_tel'],
                    'timeLast' => $it['timeLast']
                ];
            }
            $title = '物流停滞表格';
            ExcelHandle::factory('LogisticsStagnation', $title, $arr)->export();

        }
    }

    /*
     * 目的地错误
     * */
    public function wrongDestination()
    {
        //没有签收的订单中 最新更新时间与今天的间隔超过三天的订单
        $query = Logistics::query();
        $now = '"' . date('Y-m-d H:i:s') . '"';
        $raw = DB::raw("TIMESTAMPDIFF(DAY,l.zuixinshijian,$now) as timeLast,l.order_id,l.kddh,l.zuihouwuliu,o.post_receiver,o.post_tel,o.province,o.city,o.town,o.shop_name,o.local_dest_operation");
        $data = $query->from('admin_logistics as l')
            ->select($raw)
            ->leftJoin('admin_orders as o', 'o.order_id', '=', 'l.order_id')
            ->where('l.wuliuzhuangtai', 'like', '%' . '签收' . '%')
            ->where('o.local_dest_operation', 0)
            ->having('timeLast', '<', 3)
            ->get()->toArray();


        if (count($data) > 0) {
            $new_data = [];
            foreach ($data as $it) {
                if (!empty($it['province']) && !empty($it['city']) && !empty($it['town']) && !empty($it['zuihouwuliu'])) {
                    //判断是否存在
                    if (strpos($it['province'], $it['zuihouwuliu']) == false && strpos($it['city'], $it['zuihouwuliu']) == false
                        && strpos($it['town'], $it['zuihouwuliu']) == false
                    ) {
                        $new_data[] = $it;
                    }
                }
            }
            if (count($new_data) > 0) {
                $token = '907333c555896d5e87913074a545b53c4c6a90032b186fff38774bcbf39fa674';
                $obj = new \App\Lib\DingDingNotice\LogisticsWrongDest($new_data, $token, $atMobiles = [], $isAtall = false);
                $obj->sendMarkdownMessage();
            }

        }
    }

    /*
     * 通知物流可回填信息
     * */
    public function writeBackNotice()
    {
        $conditions = [
            'write_back' => 1
        ];
        $query = $this->logisticsConditions($conditions);
        $num = $query->count();
        if ($num > 0) {
            $token = '907333c555896d5e87913074a545b53c4c6a90032b186fff38774bcbf39fa674';
            $obj = new \App\Lib\DingDingNotice\LogisticsWriteBack($num, $token, $atMobiles = [], $isAtall = false);
            $obj->sendMarkdownMessage();
        }

    }


    /*
     * 物流导出
     * */
    public function noticeExp()
    {
        $conditions = [
            'write_back' => 1
        ];
        $query = $this->logisticsConditions($conditions);
        $items = $query->get()->toArray();
        if (count($items) > 0) {
            $arr = [];
            foreach ($items as $it) {
                $arr[] = [
                    'kddh' => $it['kddh'],
                    'order_id' => $it['order_id'],
                    'shop_name' => $it['shop_name'],
                    'wuliuzhuangtai' => $it['wuliuzhuangtai'],
                    'kdgs' => $it['kdgs'],
                    'zuixinshijian' => $it['zuixinshijian'],
                    'xiangxiwuliu' => $it['xiangxiwuliu']
                ];
            }
            $title = '物流回填表格';
            ExcelHandle::factory('LogisticsNotice', $title, $arr)->export();
        }

    }


    /*
     *
     * */
    public function logisticsConditions($conditions = [])
    {
        $query = Logistics::query();
        $raw = DB::raw("
            o.logistics_code,o.shop_name,l.order_id,l.kddh,l.kdgs,l.wuliuzhuangtai,
            l.zuixinshijian,l.zuihouwuliu,l.chaxunshijian,l.xiangxiwuliu
        ");
        $query->from('admin_logistics as l')
            ->select($raw)
            ->leftJoin('admin_orders as o', 'o.order_id', '=', 'l.order_id');
        if (!empty($conditions['write_back'])) {
            $query->where('o.logistics_code', '=', '')->where('l.zuixinshijian', '!=', '');
        }
        return $query;
    }

    /*
     * 物流信息同步
     * */
    public function syncLogistics()
    {
        //找出所有没有执行的任务
        $task = LogisticsTask::where('flag', 0)->first();

        if (!$task) {
            return "";
        }
        $task_id = $task->task_id;
        $res = $this->logisticsQuery($task_id);
        //把状态置1
        if ($res['flag']) {
            LogisticsTask::where('task_id', $task_id)->update([
                'flag' => 1
            ]);
        }
        $i = 0;
        //同步物流订单
        if (!empty($res['list'])) {
            foreach ($res['list'] as $item) {
                $kddh = $item['kddh'];
                $tmp_flag = Logistics::where('kddh', $kddh)->exists();
                if ($tmp_flag) {
                    $i++;
                    Logistics::where('kddh', $kddh)->update([
                        'wuliuzhuangtai' => $item['wuliuzhuangtai'],
                        'zuixinshijian' => !empty($item['zuixinshijian']) ? $item['zuixinshijian'] : null,
                        'zuihouwuliu' => $item['zuihouwuliu'],
                        'chaxunshijian' => !empty($item['chaxunshijian']) ? $item['chaxunshijian'] : null,
                        'xiangxiwuliu' => $item['xiangxiwuliu']
                    ]);
                }

            }
        }
        return $i;


    }

    /*
     * 物流任务查询
     * */
    public function logisticsQuery($taskname)
    {
        $z = new Zhuzhuyun();

        if (!$taskname) {
            throw new InvalidRequestException('缺少task_id');
        }

        $i = 1;
        $total = 0;
        $flag = false;
        $list = [];
        do {
            $res = $z->queryTask($i, $taskname);
            if ($res['code']) {
                if ($res['msg']['jindu'] == 100) {
                    $flag = true;
                    foreach ($res['msg']['list'] as $it) {
                        $list[] = $it;
                    }
                    $total = $res['msg']['totalpage'];
                }

            }
            $i++;
        } while ($i <= $total);

        return [
            'flag' => $flag,
            'list' => $list
        ];
    }

    /*
     * 创建物流任务
     * */
    public function createLogisticsTask()
    {
        $query = Logistics::query();
        $data = $query->where('wuliuzhuangtai', '!=', '已签收')->get();
        $new_data = [];
        $res = '';
        if (count($data) > 0) {
            foreach ($data as $item) {
                $new_data[] = [
                    'A' => $item->kddh,
                    'B' => $item->kdgs,
                    'C' => $item->order_id
                ];
            }
        }
        if (!empty($new_data)) {
            $res = (new \App\Http\Admin\Services\Order\OrderService())->logisticsTask($new_data);
        }
        return $res;
    }

}
